package com.ynet.middleground.riskmanage.model.qichacha;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ynet.core.common.BaseReqObjPager;
import com.ynet.core.common.PagerInfo;
import com.ynet.core.exception.BusinessException;
import com.ynet.middleground.riskmanage.bean.qichacha.operationrisk.*;
import com.ynet.middleground.riskmanage.dto.qichacha.operationrisk.*;
import com.ynet.middleground.riskmanage.external.qcc.ApiHelper;
import com.ynet.middleground.riskmanage.external.qcc.QccUriEnum;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName OperationRiskModel
 * @Description 企查查--经营风险相关服务处理类
 * @Author zhangyongbin
 * @Date 2020/8/11 16:45
 * @Version 1.0
 */
@Component
public class OperationRiskModel {

    /**
     * 数据是否存在(1-存在，0-不存在)
     **/
    private static final Integer VERIFY_RESULT = 1;

    @Autowired
    private ApiHelper apiHelper;

    @Autowired
    private Mapper mapper;

    /**
     * @return java.util.List<com.ynet.middleground.riskmanage.dto.qichacha.operationrisk.JudicialSaleCheckDTO>
     * @Description 司法拍卖核查服务处理
     * @Date 16:49 2020/8/11
     * @Param req--司法拍卖核查请求信息
     **/
    public JudicialSaleCheckInfoDTO getJudicialSaleCheckList(JudicialSaleCheckReq req) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("searchKey", req.getSearchKey());
        setReqPagingInfo(params, req);
        JSONObject apiResult = apiHelper.sendApi(QccUriEnum.GET_JUDICIAL_SALE_CHECK_LIST, params, req);
        Integer code = apiResult.getInteger("Status");
        String message = apiResult.getString("Message");
        if (!code.equals(ApiHelper.STATUS_SUCCESS)) {
            throw new BusinessException(message, String.valueOf(code));
        }
        setPageInfo(apiResult, req);

        JudicialSaleCheckInfoDTO judicialSaleCheckInfoDTO = new JudicialSaleCheckInfoDTO();

        JSONObject result = apiResult.getJSONObject("Result");

        Integer verifyResult = result.getInteger("VerifyResult");

        List<JudicialSaleCheckDTO> judicialSaleCheckList = null;

        if (verifyResult == VERIFY_RESULT) {
            JSONArray dataResult = result.getJSONArray("Data");
            judicialSaleCheckList = dataResult.toJavaList(JudicialSaleCheckDTO.class);
        }

        judicialSaleCheckInfoDTO.setVerifyResult(verifyResult);
        judicialSaleCheckInfoDTO.setData(judicialSaleCheckList);

        return judicialSaleCheckInfoDTO;
    }

    /**
     * @return java.util.List<com.ynet.middleground.riskmanage.dto.qichacha.operationrisk.LandMortgageCheckDTO>
     * @Description 土地抵押核查服务处理
     * @Date 16:50 2020/8/11
     * @Param req--土地抵押核查请求类
     **/
    public LandMortgageCheckInfoDTO getLandMortgageCheckList(LandMortgageCheckReq req) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("searchKey", req.getSearchKey());
        setReqPagingInfo(params, req);
        JSONObject apiResult = apiHelper.sendApi(QccUriEnum.GET_LAND_MORTGAGE_CHECK_LIST, params, req);
        Integer code = apiResult.getInteger("Status");
        String message = apiResult.getString("Message");
        if (!code.equals(ApiHelper.STATUS_SUCCESS)) {
            throw new BusinessException(message, String.valueOf(code));
        }
        setPageInfo(apiResult, req);

        LandMortgageCheckInfoDTO landMortgageCheckInfoDTO = new LandMortgageCheckInfoDTO();

        JSONObject result = apiResult.getJSONObject("Result");

        Integer verifyResult = result.getInteger("VerifyResult");

        List<LandMortgageCheckDTO> landMortgageCheckList = null;

        if (verifyResult == VERIFY_RESULT) {
            JSONArray dataResult = result.getJSONArray("Data");
            landMortgageCheckList = dataResult.toJavaList(LandMortgageCheckDTO.class);
        }

        landMortgageCheckInfoDTO.setVerifyResult(verifyResult);
        landMortgageCheckInfoDTO.setData(landMortgageCheckList);

        return landMortgageCheckInfoDTO;
    }

    /**
     * @return java.util.List<com.ynet.middleground.riskmanage.dto.qichacha.operationrisk.EnvPunishmentCheckDTO>
     * @Description 环保处罚核查服务处理
     * @Date 16:53 2020/8/11
     * @Param [req] --环保处罚核查请求类
     **/
    public EnvPunishmentCheckInfoDTO getEnvPunishmentCheckList(EnvPunishmentCheckReq req) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("searchKey", req.getSearchKey());
        setReqPagingInfo(params, req);
        JSONObject apiResult = apiHelper.sendApi(QccUriEnum.GET_ENV_PUNISHMENT_CHECK_LIST, params, req);
        Integer code = apiResult.getInteger("Status");
        String message = apiResult.getString("Message");
        if (!code.equals(ApiHelper.STATUS_SUCCESS)) {
            throw new BusinessException(message, String.valueOf(code));
        }
        setPageInfo(apiResult, req);

        EnvPunishmentCheckInfoDTO envPunishmentCheckInfoDTO = new EnvPunishmentCheckInfoDTO();

        JSONObject result = apiResult.getJSONObject("Result");

        Integer verifyResult = result.getInteger("VerifyResult");

        List<EnvPunishmentCheckDTO> envPunishmentCheckList = null;

        if (verifyResult == VERIFY_RESULT) {
            JSONArray dataResult = result.getJSONArray("Data");
            envPunishmentCheckList = dataResult.toJavaList(EnvPunishmentCheckDTO.class);
        }

        envPunishmentCheckInfoDTO.setVerifyResult(verifyResult);
        envPunishmentCheckInfoDTO.setData(envPunishmentCheckList);

        return envPunishmentCheckInfoDTO;
    }

    public SeriousIllegalCheckDTO getSeriousIllegalCheckList(SeriousIllegalCheckReq req) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("searchKey", req.getSearchKey());
        JSONObject apiResult = apiHelper.sendApi(QccUriEnum.GET_SERIOUS_ILLEGAL_CHECK_LIST, params, req);
        Integer code = apiResult.getInteger("Status");
        String message = apiResult.getString("Message");
        if (!code.equals(ApiHelper.STATUS_SUCCESS)) {
            throw new BusinessException(message, String.valueOf(code));
        }

        SeriousIllegalCheckDTO seriousIllegalCheckDTO = new SeriousIllegalCheckDTO();

        List<SeriousIllegalCheckDataDTO> seriousIllegalCheckDataList = null;

        JSONObject result = apiResult.getJSONObject("Result");

        Integer verifyResult = result.getInteger("VerifyResult");

        if (verifyResult == VERIFY_RESULT) {
            JSONArray data = result.getJSONArray("Data");
            seriousIllegalCheckDataList = data.toJavaList(SeriousIllegalCheckDataDTO.class);

        }

        seriousIllegalCheckDTO.setVerifyResult(verifyResult);
        seriousIllegalCheckDTO.setData(seriousIllegalCheckDataList);

        return seriousIllegalCheckDTO;
    }

    public ChattelMortgageCheckDTO getChattelMortgageCheckList(ChattelMortgageCheckReq req) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("searchKey", req.getSearchKey());
        JSONObject apiResult = apiHelper.sendApi(QccUriEnum.GET_CHATTEL_MORTGAGE_CHECK_LIST, params, req);
        Integer code = apiResult.getInteger("Status");
        String message = apiResult.getString("Message");
        if (!code.equals(ApiHelper.STATUS_SUCCESS)) {
            throw new BusinessException(message, String.valueOf(code));
        }

        ChattelMortgageCheckDTO chattelMortgageCheckDTO = new ChattelMortgageCheckDTO();

        List<ChattelMortgageCheckDataDTO> dataList = new ArrayList<>();

        ChattelMortgageCheckDataDetailDTO detail = new ChattelMortgageCheckDataDetailDTO();

        ChattelMortgageCheckDataDetailPledgeDTO pledge = null;

        List<ChattelMortgageCheckDataDetailPledgeeListDTO> pledgeeList = new ArrayList<>();

        ChattelMortgageCheckDataDetailSecuredClaimDTO securedClaim = null;

        List<ChattelMortgageCheckDataDetailGuaranteeListDTO> guaranteeList = new ArrayList<>();

        List<ChattelMortgageCheckDataDetailGuaranteeListKeyNoListDTO> keyNoList = new ArrayList<>();

        ChattelMortgageCheckDataDetailCancelInfoDTO cancelInfo = null;

        List<ChattelMortgageCheckDataDetailChangeListDTO> changeList = new ArrayList<>();

        ChattelMortgageCheckDataDebtorInfoDTO debtorInfo = null;
        // 解析JSON
        // "Result": {
        // "VerifyResult": 1,
        // "Data": [
        // {
        // "RegisterNo": "350981180010-1",
        // "RegisterDate": "2018-07-19",
        // "RegisterOffice": "福建省福安市市场监督管理局",
        // "DebtSecuredAmount": "60404.077688万元人民币",
        // "Status": "有效",
        // "Detail": {
        // "Pledge": {
        // "RegistNo": "350981180010-1",
        // "RegistDate": "2018-07-19",
        // "RegistOffice": "福建省福安市市场监督管理局"
        // },
        // "PledgeeList": [
        // {
        // "Name": "中信银行股份有限公司温州分行",
        // "IdentityType": "营业执照",
        // "IdentityNo": "913303007236389565"
        // }
        // ],
        // "SecuredClaim": {
        // "Kind": "其他债权",
        // "Amount": "60404.077688万元人民币",
        // "AssuranceScope":
        // "包括主合同项下主债权、利息、罚息、复利、违约金、损害赔偿金、及实现债权、抵押权的费用（包括但不限于诉讼费、仲裁费、律师费、差旅费、评估费、过户费、保全费、公告费、执行费等）和其他所有应付的费用。",
        // "FulfillObligation": "2018-07-19至2023-07-19",
        // "Remark": ""
        // },
        // "GuaranteeList": [],
        // "CancelInfo": null,
        // "ChangeList": null
        // },
        // "DebtorInfo": {
        // "KeyNo": "e74e02450e3f16245ffef900c60a536c",
        // "Name": "福建鼎信科技有限公司"
        // }
        // }
        // ]
        // },
        // "Status": "200",
        // "Message": "查询成功",
        // "OrderNumber": "CHATTELMORTGAGECHECK2020071618090169993390"
        // }

        JSONObject result = apiResult.getJSONObject("Result");

        Integer verifyResult = result.getInteger("VerifyResult");

        if (verifyResult == VERIFY_RESULT) {
            JSONArray data = result.getJSONArray("Data");

            JSONObject jsonObject = null;

            JSONObject jsonObjectSecond = null;

            ChattelMortgageCheckDataDTO chattelMortgageCheckDataDTO = null;

            ChattelMortgageCheckDataDetailGuaranteeListDTO chattelMortgageCheckDataDetailGuaranteeListDTO = null;

            for (int i = 0; i < data.size(); i++) {
                jsonObject = data.getJSONObject(i);
                chattelMortgageCheckDataDTO = jsonObject.toJavaObject(ChattelMortgageCheckDataDTO.class);

                JSONObject detailJSONObject = jsonObject.getJSONObject("Detail");

                if (StringUtils.isEmpty(detailJSONObject.getJSONObject("Pledge"))) {
                    pledge = new ChattelMortgageCheckDataDetailPledgeDTO();
                } else {
                    pledge = detailJSONObject.getJSONObject("Pledge")
                        .toJavaObject(ChattelMortgageCheckDataDetailPledgeDTO.class);
                }

                if (StringUtils.isEmpty(detailJSONObject.getJSONArray("PledgeeList"))) {
                    pledgeeList = new ArrayList<ChattelMortgageCheckDataDetailPledgeeListDTO>();
                } else {
                    pledgeeList = detailJSONObject.getJSONArray("PledgeeList")
                        .toJavaList(ChattelMortgageCheckDataDetailPledgeeListDTO.class);
                }

                if (StringUtils.isEmpty(detailJSONObject.getJSONObject("SecuredClaim"))) {
                    securedClaim = new ChattelMortgageCheckDataDetailSecuredClaimDTO();
                } else {
                    securedClaim = detailJSONObject.getJSONObject("SecuredClaim")
                        .toJavaObject(ChattelMortgageCheckDataDetailSecuredClaimDTO.class);
                }

                JSONArray guaranteeListJSONArray = detailJSONObject.getJSONArray("GuaranteeList");

                for (int j = 0; j < guaranteeListJSONArray.size(); j++) {
                    jsonObjectSecond = guaranteeListJSONArray.getJSONObject(j);
                    chattelMortgageCheckDataDetailGuaranteeListDTO =
                        jsonObjectSecond.toJavaObject(ChattelMortgageCheckDataDetailGuaranteeListDTO.class);

                    keyNoList = jsonObjectSecond.getJSONArray("KeyNoList") == null ? null
                        : jsonObjectSecond.getJSONArray("KeyNoList")
                            .toJavaList(ChattelMortgageCheckDataDetailGuaranteeListKeyNoListDTO.class);

                    chattelMortgageCheckDataDetailGuaranteeListDTO.setKeyNoList(keyNoList);
                    guaranteeList.add(chattelMortgageCheckDataDetailGuaranteeListDTO);
                }

                if (StringUtils.isEmpty(detailJSONObject.getJSONObject("CancelInfo"))) {
                    cancelInfo = new ChattelMortgageCheckDataDetailCancelInfoDTO();
                } else {
                    cancelInfo = detailJSONObject.getJSONObject("CancelInfo")
                        .toJavaObject(ChattelMortgageCheckDataDetailCancelInfoDTO.class);
                }

                if (StringUtils.isEmpty(detailJSONObject.getJSONArray("ChangeList"))) {
                    changeList = new ArrayList<ChattelMortgageCheckDataDetailChangeListDTO>();
                } else {
                    changeList = detailJSONObject.getJSONArray("ChangeList")
                        .toJavaList(ChattelMortgageCheckDataDetailChangeListDTO.class);
                }

                JSONObject debtorInfoJSONObject = jsonObject.getJSONObject("DebtorInfo");

                if (StringUtils.isEmpty(debtorInfoJSONObject)) {
                    debtorInfo = new ChattelMortgageCheckDataDebtorInfoDTO();
                } else {
                    debtorInfo = debtorInfoJSONObject.toJavaObject(ChattelMortgageCheckDataDebtorInfoDTO.class);
                }

                detail.setPledge(pledge);

                detail.setPledgeeList(pledgeeList);

                detail.setSecuredClaim(securedClaim);

                detail.setGuaranteeList(guaranteeList);

                detail.setCancelInfo(cancelInfo);

                detail.setChangeList(changeList);

                chattelMortgageCheckDataDTO.setDetail(detail);

                chattelMortgageCheckDataDTO.setDebtorInfo(debtorInfo);

                dataList.add(chattelMortgageCheckDataDTO);
            }
        }
        chattelMortgageCheckDTO.setVerifyResult(verifyResult);
        chattelMortgageCheckDTO.setData(dataList);

        return chattelMortgageCheckDTO;
    }

    /**
     * 设置企查查分页请求信息参数
     *
     * @param params 请求参数集合
     * @param reqPager 当前分页请求类
     */
    protected void setReqPagingInfo(Map<String, Object> params, BaseReqObjPager reqPager) {
        params.put("pageIndex", reqPager.getPagerInfo().getPageNum());
        params.put("pageSize", reqPager.getPagerInfo().getPageSize());
    }

    /**
     * 如果 api 结果返回分页信息，则将分页结果重新添加到请求分页对象中
     *
     * @param apiResult 企查查 api 结果
     * @param reqPager 请求分页信息
     */
    protected void setPageInfo(JSONObject apiResult, BaseReqObjPager reqPager) {
        JSONObject paging = apiResult.getJSONObject("Paging");
        if (paging == null) {
            return;
        }
        PagerInfo pagerInfo = reqPager.getPagerInfo();
        pagerInfo.setTotal(paging.getInteger("TotalRecords"));
    }

}
